
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sched.h>
#include <signal.h>
#define DEFAT        "\033[m\n"
#define GREEN        "\033[0;32;32m"
#define PROCESS_STACK_SIZE 8192
/*
*新进程运行函数
*/
int processFunc(void *arg)
{
    while(1){
        printf(GREEN"这里是新进程PID:%d,PPID:%d"DEFAT,getpid(),getppid());
        usleep(1000000);
    }
    return 0;
}
int main(int argc,char **argv)
{
    pid_t pid;
    int status;
    void *processStack=NULL;
    void *processStackStart=NULL;
    processStack=calloc(1,PROCESS_STACK_SIZE);
    if(!processStack){
        printf("进程栈内存分配失败\n");
        return -1;
    }
    //进程栈是从尾部开始倒查的
    processStackStart=processStack+PROCESS_STACK_SIZE;
    printf("\n\n\n\n");
    printf("********************宏伟精讲-clone()函数演示********************\n");
    printf("白色打印：父进程\n");
    printf("绿色打印：子进程\n");
    printf("clone前：PID:%d\n",getpid());
    pid=clone(processFunc,processStackStart,SIGCHLD,NULL);
    if(-1==pid){
        printf("新进程创建失败，错误码:%d\n",errno);
    }
    else{
        while(1){
            printf("新进程创建成功，clone返回值:%d\n",pid);
            usleep(1000000);
        }
        //等待子进程退出，回收僵尸进程（已退出的子进程）
        while(waitpid(pid,&status,0)<0){
            if(EINTR!=errno){
                return -1;
            }
        }
        exit(0);//父进程退出
    }
    return 0;
}